package com.weight;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.weight.data.model.Registry;
import com.weight.util.Utilities;

public class LogEntry extends Activity {

	private static final String WEIGHT_VALUE = "WEIGHT_VALUE";
	private Button _saveButton;
	private EditText _weight;
	private TextView _textDate;
	private int mYear;
	private int mMonth;
	private int mDay;
	
	static final int DATE_DIALOG_ID = 0;
	private static final String DAY_VALUE = "DAY";
	private static final String MONTH_VALUE = "MONTH";
	private static final String YEAR_VALUE = "YEAR";
	
	boolean weightKilograms = true;
	private Button _skipButton;
	private Button _options_button;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.logentry);
		
		_saveButton = (Button)  findViewById(R.id.save_button);
		_skipButton = (Button)  findViewById(R.id.skip_button);
		_options_button = (Button) findViewById(R.id.options_button);
		
		_textDate = (TextView) findViewById(R.id.labelDate);
		_weight = (EditText) findViewById(R.id.weight);	
	
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);       
		
		String selectedmeasure = pref.getString("listofmeasures", null);
		
		weightKilograms = "Kilograms".equals(selectedmeasure);
		
		_textDate.setOnClickListener(new View.OnClickListener() {		
	     
			@Override
			public void onClick(View arg0) {
				showDialog(DATE_DIALOG_ID);			
			}
		});
		
		_saveButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				float weight = 0;
				try{
					
					weight = Float.parseFloat(_weight.getText().toString());
					Calendar calendar = Calendar.getInstance();
					
					Registry.getInstance().saveLogInRegistry(calendar, weight,weightKilograms);
					callRegistryLog();
				} catch(NumberFormatException e){
					return;
				}
				
			}


		});
		
		_skipButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				callRegistryLog();
				
			}
		});
		
		_options_button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				callOptionsPage();
				
			}

			
		});
		
		if(savedInstanceState==null) {
			 // get the current date
	        final Calendar c = Calendar.getInstance();
	        mYear = c.get(Calendar.YEAR);
	        mMonth = c.get(Calendar.MONTH);
	        mDay = c.get(Calendar.DAY_OF_MONTH);
		} else {
			mYear = savedInstanceState.getInt(YEAR_VALUE);
	        mMonth = savedInstanceState.getInt(MONTH_VALUE);
	        mDay =  savedInstanceState.getInt(DAY_VALUE);
	        
	        _weight.setText(""+savedInstanceState.getFloat(WEIGHT_VALUE));
		}				
		 updateDisplay();	
	}
	
    private void callRegistryLog() {
        Intent intent = new Intent(LogEntry.this,com.weight.LogRegistry.class);
        startActivity(intent);
    }
    
    private void callOptionsPage() {
    	/**
    	 * We set temporarily the preference to false so the options page is displayed again
    	 */    	 
    	 Intent intent = new Intent(LogEntry.this,com.weight.WeightPreferences.class);
    	 intent.putExtra("optionscall", true);
         startActivity(intent);
		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case DATE_DIALOG_ID:
	    	DatePickerDialog dialog = new DatePickerDialog(this,
	                    mDateSetListener,
	                    mYear, mMonth, mDay);
	    	return dialog;
	    }
	    return null;
	}
	
	 private void updateDisplay() {
		 _textDate.setText(
	            new StringBuilder()
	                    // Month is 0 based so add 1
	                    .append(mMonth + 1).append("-")
	                    .append(mDay).append("-")
	                    .append(mYear).append(" "));
	    }
	 
	 // the callback received when the user "sets" the date in the dialog
	    private DatePickerDialog.OnDateSetListener mDateSetListener =
	            new DatePickerDialog.OnDateSetListener() {

	                public void onDateSet(DatePicker view, int year, 
	                                      int monthOfYear, int dayOfMonth) {
	                    mYear = year;
	                    mMonth = monthOfYear;
	                    mDay = dayOfMonth;
	                    updateDisplay();
	                }
	            };

		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			if(keyCode==KeyEvent.KEYCODE_BACK){
				Utilities.goToBackground(this);
				return true;
			}
			return super.onKeyDown(keyCode, event);
		}

		@Override
		protected void onSaveInstanceState(Bundle outState) {			
			super.onSaveInstanceState(outState);
			float weight = 0;
			try{
		    weight = Float.parseFloat(_weight.getText().toString());
			} catch(Exception e){
				
			}
			outState.putFloat(WEIGHT_VALUE, weight);
			
			//Save date
			outState.putInt(DAY_VALUE, mDay);
			outState.putInt(MONTH_VALUE, mMonth);
			outState.putInt(YEAR_VALUE, mYear);
			
		}
	            
	            
	  

	
	
}
